{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "归并排序，一个序列数组(无序)，如果分而治之，将前面一半和后面一半分别先排好序，然后再对两个有序的数组进行排序就比较方便了\n",
    "归并排序基于此思想，递归调用分而治之，最后再进行有序数组之间的合并。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 4, 5, 7, 8, 9, 10, 11]\n"
     ]
    }
   ],
   "source": [
    "def merge(a, b):\n",
    "    c=[]\n",
    "    a_idx = 0\n",
    "    b_idx = 0\n",
    "    while a_idx < len(a) and b_idx < len(b):\n",
    "        if a[a_idx] <= b[b_idx]:\n",
    "            c.append(a[a_idx])\n",
    "            a_idx += 1\n",
    "        else:\n",
    "            c.append(b[b_idx])\n",
    "            b_idx += 1\n",
    "    while a_idx < len(a):\n",
    "        c.append(a[a_idx])\n",
    "        a_idx += 1\n",
    "    while b_idx < len(b):\n",
    "        c.append(b[b_idx])\n",
    "        b_idx += 1\n",
    "    return c\n",
    "\n",
    "a=[1,5,8,9]\n",
    "b=[2,4,7,10,11]\n",
    "c = merge(a, b)\n",
    "print(c)\n",
    "    \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5, 8, 9]\n"
     ]
    }
   ],
   "source": [
    "def mergeSort(a):\n",
    "    a_len = len(a)\n",
    "    if a_len == 1:\n",
    "        return a\n",
    "    else:\n",
    "        a_sorted_left_half = mergeSort(a[:a_len//2])\n",
    "        a_sorted_right_half = mergeSort(a[a_len//2:])\n",
    "        a_sorted = merge(a_sorted_left_half, a_sorted_right_half)\n",
    "        return a_sorted\n",
    "\n",
    "a=[1,8,3,5,4,2,9]\n",
    "c = mergeSort(a)\n",
    "print(c)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.12 ('base')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "ad2bdc8ecc057115af97d19610ffacc2b4e99fae6737bb82f5d7fb13d2f2c186"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
